<template>
    <div class="login-container" :style="`background-image:url(${backgroundImg});'`">
        <a-form class="login-container__form" @keyup.enter="onSubmit" :rules="rules" :model="formState" ref="formRef">
            <h3 class="title">XXX管理平台登录</h3>
            <!-- 商户编号暂时用不上 -->
            <!-- <a-form-item name="custCode">
                <a-input v-model:value="formState.custCode" :maxlength="8" allowClear>
                    <template #prefix>
                        <ReconciliationOutlined />
                    </template>
                </a-input>
            </a-form-item> -->
            <a-form-item name="username">
                <a-input v-model:value="formState.username" :maxlength="50" allowClear>
                    <template #prefix>
                        <user-outlined />
                    </template>
                </a-input>
            </a-form-item>
            <a-form-item name="password">
                <a-input v-model:value="formState.password" type="password" :maxlength="50" allowClear>
                    <template #prefix>
                        <LockOutlined />
                    </template>
                </a-input>
            </a-form-item>
            <a-form-item name="code">
                <a-input v-model:value="formState.code" :maxlength="10" allowClear>
                    <template #prefix>
                        <SafetyCertificateOutlined />
                    </template>
                </a-input>
                <img class="code-img" :src="codeImgSrc" @click="getCodeImg" alt="code" />
            </a-form-item>
            <a-form-item>
                <a-checkbox v-model:checked="isRemember">记住密码</a-checkbox>
                <a href="javascript:;">忘记密码</a>
            </a-form-item>
            <a-form-item>
                <a-button class="submit-btn" type="primary" :loading="loading" @click="onSubmit">登录</a-button>
            </a-form-item>
        </a-form>
    </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, computed, onMounted } from 'vue';
import { LoginParams } from '@/types/user';
import { UserOutlined, ReconciliationOutlined, LockOutlined, SafetyCertificateOutlined } from '@ant-design/icons-vue';
import backgroundImg from '@/assets/background.jpg';
import { validators } from '@/utils';
import { Store, useStore } from 'vuex';
import { UserActionTypes, MutationType } from '@/enums/userEnums';
import { useRouter, useRoute } from 'vue-router';
import { message } from 'ant-design-vue';
import { useI18n } from 'vue-i18n';
import { getCode, getUsersType } from '@/api/user';
import { getCountry } from '@/api/merchant';

// 初始化登录信息
const initLoginForm = (isRemember: boolean, store: Store<{ [x: string]: any }>) => {
    const state: LoginParams = reactive({
        username: '',
        password: '',
        code: '',
        uuid: '',
    });
    // if isremember set saved value
    if (isRemember) {
        const { username, password } = store.state.user;
        state.username = username;
        state.password = password;
    }
    return state;
};

// 表单校验规则
const initRules = (t: fn) => {
    return {
        username: [{ required: true, message: t('yl.pleaseInputUsername'), trigger: 'blur' }],
        password: [{ required: true, message: t('yl.passwordValidator'), trigger: 'blur', validator: validators.password }],
        code: [{ required: true, message: t('yl.pleaseInputCode'), trigger: 'blur' }],
    };
};

export default defineComponent({
    name: 'login',
    components: {
        UserOutlined,
        ReconciliationOutlined,
        LockOutlined,
        SafetyCertificateOutlined,
    },
    setup() {
        const store = useStore();
        const router = useRouter();
        const route = useRoute();
        const { t } = useI18n();

        // get value from store
        const localRember = computed(() => store.state.user.isRemember);
        const isRemember = ref<boolean>(localRember.value);
        const formState: LoginParams = initLoginForm(isRemember.value, store);
        const formRef = ref();
        const rules = initRules(t);

        // code 图片路径
        const codeImgSrc = ref<string>('');
        const getCodeImg = () => {
            getCode().then((res) => {
                const { img, uuid } = res;
                formState.uuid = uuid;
                codeImgSrc.value = img;
            });
        };

        // 获取验证码
        onMounted(() => {
            getCodeImg();
        });
        // 获取区域数据
        const getCountryRegionData = async () => {
            const { content } = await getCountry();
            console.log(content);
            if (content) {
                localStorage.setItem('Region', JSON.stringify(content));
            }
        };
        const loading = ref<boolean>(false);
        // 登录
        const onSubmit = () => {
            formRef.value.validate().then(() => {
                loading.value = true;
                store.commit(MutationType.SetRemember, isRemember.value);
                store.commit(MutationType.SetName, formState.username);
                store.commit(MutationType.SetPassword, isRemember.value ? formState.password : '');

                store
                    .dispatch(UserActionTypes.Login, formState)
                    .then((res) => {
                        loading.value = false;
                        if (!res) return;
                        localStorage.setItem('userType', res.user.userInfo.type);
                        localStorage.setItem('merchantCode', res.user.user.merchantCode);
                        // // localStorage.setItem('userType', 'A');
                        message.success(t('yl.loginSuccess'));
                        if (!localStorage.Region) {
                            getCountryRegionData();
                        }
                        const to = decodeURIComponent((route.query?.redirect || '/') as string);
                        res && router.replace(to);
                    })
                    .finally(() => {
                        loading.value = false;
                    });
            });
        };

        return {
            formRef,
            formState,
            onSubmit,
            isRemember,
            backgroundImg,
            rules,
            loading,
            t,
            codeImgSrc,
            getCodeImg,
            getCountryRegionData,
        };
    },
});
</script>

<style lang="scss" scoped>
.login-container {
    @include flexCenter;
    width: 100%;
    height: 100%;
    background-color: $white;
    color: $white;
    background-size: cover;
    .title {
        font-size: 24px;
        text-align: center;
        color: #333;
        font-weight: bold;
    }

    :deep .ant-form-item-control-wrapper {
        width: 100%;
        .ant-form-item-children {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
    }

    &__form {
        border-radius: 6px;
        background: #ffffff;
        width: 320px;
        padding: 18px 25px 5px 25px;
        .code-img {
            width: 111px;
            cursor: pointer;
        }
        .submit-btn {
            width: 100%;
        }
    }
}
</style>
